<template>
	<div id="redactGoods">
		<!--<haders title="商品发布"></haders> -->
		<!--<scroller ref="scroller" >-->
			<div class="decora">
				<mt-field label="商品名称" placeholder="请输入商品名称" v-model="shopname"></mt-field>
				<li class="autos border-top">
					<span class="hdtext">是否上架</span>
					<mt-switch v-model="value"></mt-switch>
				</li>
				<mt-field label="原价" placeholder="请输入商品价格" v-model="shoppic"   type="number"></mt-field>
				<li class="autos border-top" @click="isShow">
					<span class="hdtext">拼团时间</span>
					<p class="auto_fontz">{{duration}}</p> 
				</li> 
				<!--<mt-field label="拼团时间" placeholder="请选择拼团持续时间" v-model="duration" @click.native="isShow"></mt-field>-->
				<mt-field label="拼团价" placeholder="设置低价金额" v-model="lowprice" type="number"></mt-field>
				<mt-field label="参团人数" placeholder="设置最多参团人数" v-model="peoples" type="number"></mt-field>
				<li class="autos border-top">
					<span class="hdtext">时间范围</span>
					<font @click="openPicker()">{{timeOne|tiems}}</font>~
					<font @click="openPickerTwo()">{{timeTwo | tiems}}</font>
				</li>
				<mt-field label="商品库存" placeholder="请输入商品库存" v-model="inventory" type="number"></mt-field>
				<mt-field label="商品排序" placeholder="数字越大越靠前" v-model="sort" type="number"></mt-field>
				<mt-field label="商品编码" placeholder="请输入商品编码" v-model="encoding">
					<!--<span>扫码</span>--></mt-field>
				<mt-radio title="物流方式" v-model="physical" :options="options">
				</mt-radio>
				<mt-field label="运费" placeholder="不填则无运费" v-model="freight" type="number"></mt-field>
				<mt-field label="商品简介" placeholder="商品简介" v-model="brief"></mt-field>
				<li class="imgAuto">
					<p class="mhaser">
						<span>
							<font>商品展示图</font>
							<font>建议尺寸 900*500</font>
						</span>
						<a>上传图片</a>
						<input type="file" @change="imgUpload($event,uploadImg,1)" class="hides" />
					</p>
					<p class="imgone">
						<img v-for="item in uploadImg" :src="item" alt="加载失败" :onerror="imgError" />
					</p>
				</li>
				<li class="imgAuto">
					<p class="mhaser">
						<span>
							<font>商品轮播图</font>
							<font>建议尺寸 900*500</font>
						</span>
						<a>上传图片</a>
						<input type="file" @change="imgUpload($event,uploadImgTwo)" class="hides" />
					</p>
					<div class="imgTwo" style="overflow: hidden;">
						<div class="left_f vesselimg" style="width: 80%;">
							<a style="width:33%;padding-right:0.15rem;" v-for="item,index in uploadImgTwo">
								<img  :src="item.imgs"/>
								<i class="iconfont icon-shanchu" @click="reovmImg(item,uploadImgTwo,shufImg)"></i>
								<span v-if="shuftype" class="layespan" @click="paixu(item,uploadImgTwo,shufImg,onetypeImg)"><font v-show="item.num">{{item.num}}</font> </span>
							</a> 
						</div>
						<div class="right_f vesselbut" style="width: 20%;">
							<font>依次点击排序</font>
							<a class="paixubut" :class="{butaction:shuftype}" @click="butran(shuftype,onetypeImg)"  >排序</a>
							<a v-if="shuftype" class="paixubut" :class="{butaction:shuftype}" @click="butagain(uploadImgTwo,shufImg,onetypeImg)"  >重新排序</a> 
						</div> 
						
						<!--<grid :draggable="true" :sortable="true" :items="uploadImgTwo">
							<template slot="cell" scope="props">
								<a @touchend="touchend(props,uploadImgTwo)">
									<img :src="props.item" alt="加载失败" :onerror="imgError" />
									<i class="iconfont icon-shanchu" @click="thisreovm(props,uploadImgTwo)"></i>
								</a>
							</template>
						</grid>-->
					</div>
				</li>
				<li class="imgAuto">
					<p class="mhaser">
						<span>
							<font>商品详情图|测试</font>
							<font>建议尺寸 900*500</font>
						</span>
						<a>上传图片</a>
						<input type="file" @change="imgUpload($event,uploadImgThree)" class="hides" />
					</p>
					<div class="imgTwo" style="overflow: hidden;">
						<div class="left_f vesselimg" style="width: 80%;">
							<a style="width:33%;padding-right:0.15rem;" v-for="item,index in uploadImgThree">
								<img  :src="item.imgs"/>
								<i class="iconfont icon-shanchu" @click="reovmImg(item,uploadImgThree,newImg)"></i>
								<span v-if="ranktype" class="layespan" @click="paixu(item,uploadImgThree,newImg,twotypeImg)"><font v-show="item.num">{{item.num}}</font> </span>
							</a> 
						</div>
						<div class="right_f vesselbut" style="width: 20%;">
							<font>依次点击排序</font>
							<a class="paixubut" :class="{butaction:ranktype}" @click="butran(ranktype,twotypeImg)"  >排序</a>
							<a v-if="ranktype" class="paixubut" :class="{butaction:ranktype}" @click="butagain(uploadImgThree,newImg,twotypeImg)"  >重新排序</a> 
						</div> 
						<!--<grid :draggable="true" :sortable="true" :items="uploadImgThree">
							<template slot="cell" scope="props">
								<a @touchend="touchend(props,uploadImgThree)">
									<img :src="props.item" alt="加载失败" :onerror="imgError" />
									<i class="iconfont icon-shanchu" @click="thisreovm(props,uploadImgThree)"></i>
								</a>
							</template>
						</grid>-->
					</div>
				</li>
				<li class="textares border-top">
					<textarea placeholder="商品详情文本编辑" v-model="textdetails" ref="textAotu" ></textarea>
				</li>

			</div> 
		<!--</scroller>-->
		
		<footer>
			<a @click="getAlldata">确认发布</a>
		</footer>

		<mt-datetime-picker ref="picker" type="datetime" v-model="pickerValue" @confirm="handleConfirm" year-format="{value}年" month-format="{value}月" date-format="{value}日" hour-format="{value}时" minute-format="{value}分" :startDate="startDate">
		</mt-datetime-picker>

		<mt-datetime-picker ref="pickerTwo" type="datetime" v-model="pickerValueTwo" @confirm="handleConfirmTwo" year-format="{value}年" month-format="{value}月" date-format="{value}日" hour-format="{value}时" minute-format="{value}分" :startDate="startDateTwo">
		</mt-datetime-picker>

		<!--选择持续时间-->
		<mt-popup v-model="popupVisible" position="bottom">
			<div class="selset">
				<mt-picker :slots="slots" value-key="text" :defaultIndex="1"  @change="onValuesChange"></mt-picker>
			</div>
		</mt-popup>

	</div>
</template>
<script>
	import { Field } from 'mint-ui';
	import { Radio } from 'mint-ui';
	import { DatetimePicker } from 'mint-ui';
	import { Toast } from 'mint-ui';
	import Qs from 'qs';
	import { Indicator } from 'mint-ui';
	export default {
		name: 'redactGoods',
		components: {
			Field,
			Radio,
			DatetimePicker
		},
		data() {
			return { 
				shopId: '',
				shopname: '',
				value: true,
				shoppic: '',
				lowprice: '',
				peoples: '',
				inventory: '',
				sort: '',
				encoding: '',
				physical: '',
				options: [{
						label: '自提',
						value: 1
					},
					{
						label: '快递',
						value: 2
					}
				], //选择物流
				freight: '',
				brief: '',
				imgOne: [],
				imgTwo: [],
				imgthree: [],
				textdetails: '',
				pickerValue: '',
				pickerValueTwo: '',
				startDate: new Date(),
				startDateTwo: new Date(),
				timeOne: '开始时间',
				timeTwo: '结束时间',
				uploadImg: [],
				uploadImgTwo: [],
				uploadImgThree: [],
				duration: "选择拼团时间", //持续时间文本
				tiemNum: '', //持续时间的val值
				popupVisible: false,
				slots: [{
					flex: 1,
					values: [{
							text: "1天",
							val: 1
						},
						{
							text: "2天",
							val: 2
						},
						{
							text: "3天",
							val: 3
						},
						{
							text: "4天",
							val: 4
						},
						{
							text: "5天",
							val: 5
						},
						{
							text: "6天",
							val: 6
						},
						{
							text: "7天",
							val: 7
						},
						{
							text: "8天",
							val: 8
						}, {
							text: "9天",
							val: 9
						},
					],
					className: 'slot1'
				}],
				newImg:[],
				isSort:true,
				ranknumber:1,
				ranktype:false,
				shufImg:[],
				shuftype:false,
				shufnumber:1,
				isShuf:true,  
				allData:"",//添加商品上传参数集
				onetypeImg:1,//区别商品轮播图
				twotypeImg:2,//区别商品详情图
			}
		},
		created() {
			this.imgError = this.$store.state.imgError;
		},
		mounted() {
			this.inputBugFix();
			this.GoodsId = this.$route.params.GoodsId; //获取商品ID
			this.getGoodsDetails(); //获取商品详情
			


		},
		methods: {
			inputBugFix() {
		    window.addEventListener('resize', function () {
			        if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
			            window.setTimeout(function () {
			                document.activeElement.scrollIntoViewIfNeeded();
			            }, 0);
			        }
			    })
			}, 
			getAlldata() { 
				this.publishGoods(); 
			},
			isShow() {
				//显示选择拼团时间
				console.log(123);
				this.popupVisible = true;
			},
			//选择拼团持续时间
			onValuesChange(picker, values) {
				this.duration = values[0].text;
				this.tiemNum = values[0].val;
			},
			//图片删除
			thisreovm(props, uploadWho) {
				uploadWho.splice(props.index, 1);
			},
			//图片移动
			touchend(props, uploadWho) {
				console.log(props);
				uploadWho.splice(props.index, 1);
				uploadWho.splice(props.sort, 0, props.item);
			},
			//图片上传
			imgUpload(ev, uploadWho, num) {
				let img = ev.target.files[0],
					image = new Image(),
					maxSize = 1024 * 1024 * 10;

				// 判断是否图片
				if(!img) {
					return;
				}
				// 判断图片格式
				if(!(img.type.indexOf('image') == 0 && img.type && /\.(?:jpg|png|gif|jpeg|bmp)$/.test(img.name))) {
					return Toast({
						message: '只能上传jpg,png,gif,jpeg图片',
						position: 'center',
						duration: 2000
					});
				}
				let reader = new FileReader();
				let that = this;
				reader.onload = function(e) {
					if(this.result.length > maxSize) {
						return Toast({
							message: '图片不能大于10MB',
							position: 'center',
							duration: 2000
						});
					}
					let url = reader.result;
					if(num) {
						that.$set(uploadWho, 0, url);
					} else {
						uploadWho.push({imgs:url});
					}
					console.log(uploadWho);
					ev.target.value = '';

				}
				reader.readAsDataURL(img);
			},
			//点击选择时间
			openPicker() {
				this.$refs.picker.open();
			},
			openPickerTwo() {
				this.$refs.pickerTwo.open();
			},
			handleConfirm(picker) {
				console.log(picker);
				let times = new Date(picker);
				this.startDateTwo = picker;
				let month = times.getMonth() + 1,
					dates = times.getDate(),
					hour = times.getHours(),
					minutes = times.getMinutes();
				if(month < 10) {
					month = "0" + month;
				}
				if(dates < 10) {
					dates = "0" + dates;
				}
				if(hour < 10) {
					hour = "0" + hour;
				}
				if(minutes < 10) {
					minutes = "0" + minutes;
				}
				this.timeOne = times.getFullYear() + '-' + month + '-' + dates + ' ' + hour + ':' + minutes;

			},
			handleConfirmTwo(picker) {
				let times = new Date(picker);
				let month = times.getMonth() + 1,
					dates = times.getDate(),
					hour = times.getHours(),
					minutes = times.getMinutes();
				if(month < 10) {
					month = "0" + month;
				}
				if(dates < 10) {
					dates = "0" + dates;
				}
				if(hour < 10) {
					hour = "0" + hour;
				}
				if(minutes < 10) {
					minutes = "0" + minutes;
				}
				this.timeTwo = times.getFullYear() + '-' + month + '-' + dates + ' ' + hour + ':' + minutes;
			},
			//获取商品详情
			getGoodsDetails() {
				let _this = this;
				if(_this.GoodsId) {
					Indicator.open({
						text: '初始化中...'
					});
					_this.$http.get("/ManagerGroupBuy/GetManageGoodsDetails", {
						params: {
							"goodsId": _this.GoodsId
						}
					}).then((res) => {
						if(res.data.code == 1) {
							let items = res.data.data;
							_this.shopId = items.ShopId; //商家ID
							_this.shopname = items.GoodsName;
							_this.value = items.GoodsStatus; //是否上架
							_this.shoppic = items.OldPrice;
							_this.lowprice = items.GroupPrice; //拼团价格
							_this.peoples = items.GroupCount; //拼团人数
							_this.inventory = items.StockCount; //库存量
							_this.sort = items.SortNumber; //商品序号
							_this.encoding = items.GoodsCode; //商品编码
							_this.physical = items.DeliveryType; //物流方式
							_this.freight = items.FreightPrice; //运费
							_this.brief = items.GoodsAbout; //商品简介
							_this.textdetails = items.GoodsDesc; //商品介绍 
							_this.uploadImg[0] = items.GoodsImg; //商品展示图 
							//_this.uploadImgTwo = items.CarouselImgs; //商品轮播图 
							_this.timeOne = items.BeginTime; //开始时间
							_this.timeTwo = items.EndTime; //结束时间  
							_this.duration=items.KeepTime+"天";
							_this.tiemNum = items.KeepTime; //持续时间 
							//详情图
							items.CarouselImgs.forEach(function(data){
								 _this.uploadImgTwo.push({imgs:data})
							}) 
							items.DetailsImgs.forEach(function(data){
								 _this.uploadImgThree.push({imgs:data})
							}) 
							Indicator.close();
						} else {
							Toast(res.data.msg);
							Indicator.close();
						} 
					}).catch((err) => {
						Toast(err);
						console.log(err)
					});

				}
			}, //添加商品信息
			publishGoods() {
				let _this = this; 
				
				if(_this.shopname==""){
					Toast("请填写商品名称");
				}else if(_this.shoppic==""){
					Toast("请填写商品原价");
				}else if(_this.lowprice==""){
					Toast("请填写商品拼团价");
				}else if(_this.tiemNum==""){
					Toast("请选择拼团持续时间");
				}else if(_this.peoples==""){
					Toast("请填写参团人数");
				}else if(_this.timeOne==""|| _this.timeOne=="开始时间"){
					Toast("请选择开始时间"); 
				}else if(_this.timeTwo==""||_this.timeTwo=="结束时间"){
					Toast("请选择结束时间");
				}else if(_this.inventory==""){
					Toast("请填写商品库存");
				}else if(_this.sort==""){
					Toast("请填写商品序号");
				}else if(_this.encoding==""){
					Toast("请填写商品编码");
				}else if(_this.physical==""){
					Toast("请选择物流方式");
				}else if(_this.uploadImg==""){
					Toast("请上传商品展示图 ");
				}else if(_this.uploadImgTwo==""){
					Toast("请上传商品轮播图");
				}else{
					Indicator.open({
						text: '信息提交中...'
					});
					
					_this.allData = {
					/* shopId:92,*/
					goodsName: _this.shopname,
					goodsStatus: _this.value ? 1 : 0,
					price: _this.shoppic,
					groupPrice: _this.lowprice,
					keepTime: _this.tiemNum,
					keepType: 2,
					groupCount: _this.peoples,
					beginTime: _this.timeOne,
					endTime: _this.timeTwo,
					stockCount: _this.inventory,
					sortNumber: _this.sort,
					goodsCode: _this.encoding,
					deliveryType: _this.physical,
					freightPrice: _this.freight,
					goodsImgStr: _this.uploadImg.join(""),
					goodsAbout: _this.brief,
					goodsDesc: _this.textdetails,
					carouselStr: [],
					detailsStr:[],
				}    
					_this.isImgitem(_this.onetypeImg,_this.isShuf,_this.uploadImgTwo,_this.allData,_this.shufImg)
				 	_this.isImgitem(_this.twotypeImg,_this.isSort,_this.uploadImgThree,_this.allData,_this.newImg)
				 	
					if(_this.GoodsId) {
						//如果有产品ID 
						_this.allData.id = _this.GoodsId;
					}
					console.log(_this.allData)  
					this.$http.post('/ManagerGroupBuy/PublishGoods', Qs.stringify(
							_this.allData
						)).then((res) => { 
					if(res.data.code == 1) {
						console.log(res.data);
						_this.$router.push({
							path:'/merchant/manageGoods'
						})
						Indicator.close();
					} else { 
						Toast(res.data.msg); 
						Indicator.close();
					}
						
					}).catch((err) => { 
						console.log(err);
						Indicator.close();
					});
				}
			},
			//显示排序模态框
			butran(type,typeImg){
				if(typeImg===1){
					this.shuftype =!type;	
				}else{
					this.ranktype =!type;	
				}
				 
			},
			//点击排序
			paixu(item,Imgitem,newitem,typeImg){ 
				let _this=this;
			 	let leng=Imgitem.length;
			 	if(typeImg===1){
			 		if(_this.shufnumber>leng){
					return;
					} 
					if(item.num){
						return;
					}else{
						_this.$set(item,'num',_this.shufnumber++)
						 newitem.push(item.imgs); 
						 _this.isShuf=false; 
					} 
			 	}else{
			 		if(_this.ranknumber>leng){
					return;
					} 
					if(item.num){
						return;
					}else{
						_this.$set(item,'num',_this.ranknumber++)
						 newitem.push(item.imgs); 
						 _this.isSort=false; 
					} 
			 	} 
			},
			//重新开始排序
			butagain(Imgitem,newitem,typeImg){ 
				let _this=this; 
				if(typeImg===1){
					_this.shufnumber=1;
					_this.isShuf=true;
					_this.shufImg=[];  
				}else{
					_this.ranknumber=1;
					_this.isSort=true;
					_this.newImg=[];  
				}
				Imgitem.forEach(function(data){
					data.num=""; 
				}) 
			},
			//删除图片
			reovmImg(item,Imgitem,newitem){
					let _this=this; 
				  for(var i=0; i<Imgitem.length; i++) {
				    if(Imgitem[i].imgs == item.imgs) {
				      Imgitem.splice(i, 1);
				      break;
				    }
				  }
				  for(var i=0; i<newitem.length; i++) {
				    if(newitem[i] == item.imgs) {
				      newitem.splice(i, 1);
				      break;
				    }
				  } 
			},
			//判断传给后台的参数
			isImgitem(typeImg,typeitem,Imgitem,pushdata,newitem){ 
				 	if(typeitem){ 
						let imdata=[];
						if(Imgitem==""){
							Toast("请上传图片");
							return;
						} 
						Imgitem.forEach(function(data){ 
							imdata.push(data.imgs);
							if(typeImg===1){
								pushdata.carouselStr=imdata.join("|");
							}else{
								pushdata.detailsStr=imdata.join("|");
							} 
						}) 
					}else{ 
						if(newitem==""){
							Toast("请选择排序");
							return;
						} 
						if(Imgitem.length>newitem.length){
							Toast("排序未完成，如有不需要请删除"); 
						}else{ 
							if(typeImg===1){
								pushdata.carouselStr= newitem.join("|")
							}else{
								pushdata.detailsStr= newitem.join("|");
							} 
						} 
					}  
			}, 
		},
		filters: {
			tiems: function(val) {
				if(!val) {
					return ''
				} else {
					return val.replace(/(T|\.\d+)/gim, " ");
				}
			},
			money: function(val) {
				if(!val) {
					val = 0.00;
				} else {
					val = Number(val).toFixed(2);
				}
				return val
			}
		}

	}
</script>
<style scoped>
	#haders{
		position: fixed !important;
	} 
	.decora { 
		padding-bottom: 1.3rem;
		overflow-y: auto;
	}
	
	footer {
		position:fixed;
		width: 100%;
		left: 0;
		bottom: 0;
		z-index: 100;
		height: 1.3rem;
		line-height: 1.4rem;
	}
	
	footer a {
		display: block;
		width: 100%;
		text-align: center;
		font-size: 0.453333rem;
		color: #fff;
		font-weight: 500;
		border-top-left-radius: 0.066666rem;
		border-top-right-radius: 0.066666rem;
		background-color: #6530E0;
	}
	
	.autos {
		width: 100%;
		background-color: #fff;
		display: flex;
		padding: 0.2rem 0;
		align-items: center;
	}
	
	.border-top {
		border-top: 1px solid #CCCCCC;
	}
	
	.border-bottom {
		border-bottom: 1px solid #CCCCCC;
	}
	
	.autos .hdtext {
		font-size: 0.4rem;
		margin-left: 0.2rem;
		margin-right: 1rem;
	}
	
	.autos font {
		font-size: 0.32rem;
		display: inline-block;
		padding: 0.15rem 0;
		width: 32%;
		color: #666666;
	}
	
	.autos font:nth-child(3) {
		margin-left: 3%;
	}
	
	.imgAuto {
		width: 100%;
		background-color: #fff;
		padding: 0 0.3rem 0.2rem 0.3rem;
		border-top: 1px solid #ccc;
	}
	
	.imgAuto .mhaser {
		width: 100%;
		display: flex;
		height: 1.2rem;
		justify-content: space-between;
		align-items: center;
		position: relative;
	}
	
	.imgAuto .mhaser span {
		display: flex;
		flex-direction: column;
		font-size: 0.373333rem;
		justify-content: space-around;
	}
	
	.imgAuto .mhaser span font:nth-child(2) {
		font-size: 0.32rem;
		color: #6530E0;
	}
	
	.imgAuto .mhaser a {
		display: inline-block;
		padding: 0.2rem;
		background: linear-gradient(-92deg,#8900e0 0%, #1896e0 180%);
		color: #fff;
		border-radius: 0.066666rem;
	}
	
	.imgone {
		border-top: 1px dashed #ccc;
		padding: 0.2rem;
	}
	
	.imgone img {
		width: 100%;
		max-height: 5rem;
	}
	
	.imgTwo {
		border-top: 1px dashed #ccc;
		padding: 0.2rem 0;
		/*overflow: hidden;*/
	}
	
	.imgTwo a {
		display: inline-block;
		/*float: left;*/
		width: 95%;
		height: 95%;
		/*margin-right:3.333333333%;
		margin-bottom: 0.2rem;*/
		/*border-radius: 0.133333rem;*/
		overflow: hidden;
		position: relative;
	}
	
	.imgTwo a img {
		width: 100%;
		height: 100%;
	}
	
	.hides {
		position: absolute;
		right: 0;
		width: 1.5rem;
		height: 1rem;
		opacity: 0;
	}
	
	.icon-shanchu {
		color: #DF4444;
		position: absolute;
		bottom: 0.01rem;
		right: 0.01rem;
		z-index: 20;
		font-size: 0.64rem;
	}
	
	.textares {
		width: 100%;
		padding: 0.2rem 0.3rem;
		background-color: #fff;
	}
	
	.textares textarea {
		width: 100%;
		height: 5rem;
		padding: 0.2rem;
		border-radius: 0.2rem;
		resize: none;
		font-size: 0.32rem;
		color: #666;
	}
	.auto_fontz{
		font-size: 0.373333rem;
		color: #888;
	} 
	.layespan{ 
	    position: absolute;
	    width: 95%;
	    height: 100%; 
	    bottom:0;
	    left:0;
	    z-index: 22;
	    text-align: center;
	    display: flex;
	    background:rgba(0,0,0,0.5);
	    justify-content: center;
	    align-items: center;
	    color: #fff;
	}
	.layespan font{
		display: inline-block;
		color: #fff;
		background-color:#6530E0;
		width: 0.6rem;
		height: 0.6rem;
		border-radius:100%;
		line-height: 0.6rem;
		position: absolute; 
		z-index: -1;
		
	}
	 .paixubut{
	 	display: inline-block;
	 	padding: 0.2rem;
	 	background:#ccc;
	 	color: #fff;
	 	border-radius: 0.066666rem;
	 	text-align: center;
	 	margin-top: 0.2rem; 
	 }
	 .butaction{
	 	
	 	background: linear-gradient(-92deg, #8900e0 0%, #1896e0 180%);  
	 }
	 .vesselbut font{
	 	color: #6530E0;
	 	
	 }
</style>